<template>
  <div class="playback" id="if-box">
    <div class="playback-tite">
      <div class="flex">
        <div class="img-box">
          <img src="@/assets/ivr/icon_condition.svg" alt="" class="w-16 h-16" />
        </div>
        <div class="titles">{{ nodeName }}</div>
      </div>
      <div>
        <el-popover placement="bottom" trigger="click" width="100">
          <div class="node-list">
            <div class="p-8" @click="copyNode">复制</div>
            <el-divider style="margin: 4px 0" />
            <div class="p-8" @click.stop="delNode">删除</div>
          </div>
          <template #reference>
            <svg
              t="1744771665484"
              class="icon cursor-pointer"
              viewBox="0 0 1024 1024"
              version="1.1"
              xmlns="http://www.w3.org/2000/svg"
              p-id="5189"
              width="16"
              height="16"
            >
              <path
                d="M97.95349285 509.99901215m-94.17807172 0a94.17807171 94.17807171 0 1 0 188.35614346 0 94.17807171 94.17807171 0 1 0-188.35614346 0Z"
                fill="#2c2c2c"
                p-id="5190"
              ></path>
              <path
                d="M510.81520458 509.99901215m-94.17807172 0a94.17807171 94.17807171 0 1 0 188.35614344 0 94.17807171 94.17807171 0 1 0-188.35614344 0Z"
                fill="#2c2c2c"
                p-id="5191"
              ></path>
              <path
                d="M923.6769163 509.99901215m-94.17807172 0a94.17807171 94.17807171 0 1 0 188.35614343 0 94.17807171 94.17807171 0 1 0-188.35614343 0Z"
                fill="#2c2c2c"
                p-id="5192"
              ></path>
            </svg>
          </template>
        </el-popover>
      </div>
    </div>
    <div class="playback-content p-16px">
      <el-form :model="formState">
        <el-form-item label="节点名称" required>
          <el-input v-model="formState.name" @input="updateProperties" />
        </el-form-item>
        <el-form-item>
          <template #label>
            <el-text style="margin-left: 10px">执行条件</el-text>
          </template>
          <div class="flex">
            <el-text style="flex-shrink: 0">前置</el-text>
            <el-select
              v-model="formState.if_type"
              @change="updateProperties"
              style="width: 100px; margin: 0 5px"
              placeholder="请选择"
            >
              <el-option
                v-for="item in ifTypeOption"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              >
              </el-option>
            </el-select>
            <el-text>连线节点执行完,执行当前节点</el-text>
          </div>
        </el-form-item>
        <!-- if -->
        <div class="if_box">
          <h6 style="margin: 0; margin-bottom: 10px">IF</h6>
          <div
            class="flex gap"
            style="margin-bottom: 10px"
            v-for="(ifItem, index) in formState.if_matching"
            :key="'if-' + index"
          >
            <el-select
              v-model="ifItem.nodeId"
              @change="updateProperties"
              style="flex: 1"
              placeholder="请选择IF条件"
            >
              <el-option
                v-for="item in formState.ifOption"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              >
              </el-option>
            </el-select>
            <el-select
              v-model="ifItem.query"
              @change="updateProperties"
              style="flex: 1"
              placeholder="请选择"
            >
              <el-option
                v-for="item in conditionOption"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              >
              </el-option>
            </el-select>
            <el-input
              style="flex: 1"
              @input="updateProperties"
              v-if="ifItem.query != 13 && ifItem.query != 14"
              v-model="ifItem.value"
              placeholder="请输入值"
            ></el-input>
            <svg
              :class="index == 0 ? 'dis' : ''"
              style="cursor: pointer"
              @click="delIf(index)"
              t="1756090886598"
              class="icon"
              viewBox="0 0 1024 1024"
              version="1.1"
              xmlns="http://www.w3.org/2000/svg"
              p-id="3344"
              width="20"
              height="20"
            >
              <path
                d="M739.328 915.968H284.672c-40.448 0-73.216-32.768-73.216-73.216V276.48c0-16.384 13.312-29.184 29.184-29.184s29.184 13.312 29.184 29.184v566.272c0 8.192 6.656 14.848 14.848 14.848h454.144c8.192 0 14.848-6.656 14.848-14.848V276.48c0-16.384 13.312-29.184 29.184-29.184s29.184 13.312 29.184 29.184v566.272c0.512 40.448-32.768 73.216-72.704 73.216z"
                p-id="3345"
                fill="#f56c6c"
              ></path>
              <path
                d="M871.936 283.648H152.064c-16.384 0-29.184-13.312-29.184-29.184 0-16.384 13.312-29.184 29.184-29.184h720.384c16.384 0 29.184 13.312 29.184 29.184 0 15.872-13.312 29.184-29.696 29.184zM434.688 784.384c-16.384 0-29.184-13.312-29.184-29.184V374.272c0-16.384 13.312-29.184 29.184-29.184s29.184 13.312 29.184 29.184V755.2c0 15.872-13.312 29.184-29.184 29.184zM607.744 784.384c-16.384 0-29.184-13.312-29.184-29.184V374.272c0-16.384 13.312-29.184 29.184-29.184s29.184 13.312 29.184 29.184V755.2c0.512 15.872-12.8 29.184-29.184 29.184zM570.368 166.4H453.632c-16.384 0-29.184-13.312-29.184-29.184s13.312-29.184 29.184-29.184H570.88c16.384 0 29.184 13.312 29.184 29.184S586.752 166.4 570.368 166.4z"
                p-id="3346"
                fill="#f56c6c"
              ></path>
            </svg>
          </div>
          <div>
            <el-button type="primary" @click="addIf" link> + 添加分支</el-button>
          </div>
        </div>
        <!-- if - else-->
        <div class="if_box">
          <h6 style="margin: 0; margin-bottom: 10px">ELSE-IF</h6>
          <div
            class="flex gap"
            style="margin-bottom: 10px"
            v-for="(ifElseItem, index2) in formState.if_else_matching"
            :key="'if' + index2"
          >
            <el-select
              @change="updateProperties"
              v-model="ifElseItem.nodeId"
              style="flex: 1"
              placeholder="请选择IF条件"
            >
              <el-option
                v-for="item in formState.ifOption"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              >
              </el-option>
            </el-select>
            <el-select
              @change="updateProperties"
              v-model="ifElseItem.query"
              style="flex: 1"
              placeholder="请选择"
            >
              <el-option
                v-for="item in conditionOption"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              >
              </el-option>
            </el-select>
            <el-input
              style="flex: 1"
              @input="updateProperties"
              v-if="ifElseItem.query != 13 && ifElseItem.query != 14"
              v-model="ifElseItem.value"
              placeholder="请输入值"
            ></el-input>
            <svg
              style="cursor: pointer"
              t="1756090886598"
              class="icon"
              viewBox="0 0 1024 1024"
              version="1.1"
              xmlns="http://www.w3.org/2000/svg"
              p-id="3344"
              width="20"
              height="20"
              :class="index2 == 0 ? 'dis' : ''"
              @click="clearElse(index2)"
            >
              <path
                d="M739.328 915.968H284.672c-40.448 0-73.216-32.768-73.216-73.216V276.48c0-16.384 13.312-29.184 29.184-29.184s29.184 13.312 29.184 29.184v566.272c0 8.192 6.656 14.848 14.848 14.848h454.144c8.192 0 14.848-6.656 14.848-14.848V276.48c0-16.384 13.312-29.184 29.184-29.184s29.184 13.312 29.184 29.184v566.272c0.512 40.448-32.768 73.216-72.704 73.216z"
                p-id="3345"
                fill="#f56c6c"
              ></path>
              <path
                d="M871.936 283.648H152.064c-16.384 0-29.184-13.312-29.184-29.184 0-16.384 13.312-29.184 29.184-29.184h720.384c16.384 0 29.184 13.312 29.184 29.184 0 15.872-13.312 29.184-29.696 29.184zM434.688 784.384c-16.384 0-29.184-13.312-29.184-29.184V374.272c0-16.384 13.312-29.184 29.184-29.184s29.184 13.312 29.184 29.184V755.2c0 15.872-13.312 29.184-29.184 29.184zM607.744 784.384c-16.384 0-29.184-13.312-29.184-29.184V374.272c0-16.384 13.312-29.184 29.184-29.184s29.184 13.312 29.184 29.184V755.2c0.512 15.872-12.8 29.184-29.184 29.184zM570.368 166.4H453.632c-16.384 0-29.184-13.312-29.184-29.184s13.312-29.184 29.184-29.184H570.88c16.384 0 29.184 13.312 29.184 29.184S586.752 166.4 570.368 166.4z"
                p-id="3346"
                fill="#f56c6c"
              ></path>
            </svg>
          </div>
          <div>
            <el-button type="primary" @click="addIfElse" link> + 添加分支</el-button>
          </div>
        </div>
        <div class="if_box">
          <h6 style="margin: 0; margin-bottom: 10px">ELSE</h6>
        </div>
      </el-form>
    </div>
  </div>
</template>

<script lang="ts">
import { defineComponent, createVNode } from 'vue'
import { useIvrStore } from '@/store/modules/ivr'
import { generateRandomString } from '@/utils/node'
import { getIvrVoiceAll } from '@/api/call/voiceManagement'
import { cloneDeep } from 'lodash-es'
import { RecordApi } from '@/api/call/record'
import { emitter } from '@/utils/eventBus'

const useStore = useIvrStore()
export default defineComponent({
  name: 'LfNode',
  inject: ['getNode', 'getGraph'],
  data() {
    return {
      formState: {
        if_type: '1',
        if_matching: [],
        if_else_matching: [],
        if_next: '',
        if_else_next: '',
        else_next: '',
        name: '',
        ifOption: []
      },
      ifTypeOption: [
        {
          label: '所有',
          value: '1'
        },
        {
          label: '任一',
          value: '2'
        }
      ],
      conditionOption: [
        {
          label: '包含',
          value: '1'
        },
        {
          label: '不包含',
          value: '2'
        },
        {
          label: '等于',
          value: '3'
        },
        {
          label: '大于',
          value: '4'
        },
        {
          label: '大于等于',
          value: '5'
        },
        {
          label: '小于',
          value: '6'
        },
        {
          label: '小于等于',
          value: '7'
        },
        {
          label: '长度等于',
          value: '8'
        },
        {
          label: '长度大于',
          value: '9'
        },
        {
          label: '长度大于等于',
          value: '10'
        },
        {
          label: '长度小于等于',
          value: '11'
        },
        {
          label: '长度小于',
          value: '12'
        },
        {
          label: '为真',
          value: '13'
        },
        {
          label: '不为真',
          value: '14'
        }
      ],
      nodeName: '',
      id: 'if_',
      nodeIdx: ''
    }
  },
  mounted() {
    const node = (this as any).getNode()
    const graph = (this as any).getGraph()
    const { nodes } = graph
    const index = nodes.findIndex((item) => item.id == node.id)
    const playbackArr = nodes.filter((item) => item.properties.businessType == 2)
    const {
      if_type,
      name,
      nodeIndex,
      nodeName,
      if_matching,
      if_else_matching,
      if_next,
      if_else_next,
      else_next,
      ifOption
    } = nodes[index].properties
    this.nodeIdx = nodeIndex
    this.nodeName = nodeName + (nodeIndex == 0 ? '' : nodeIndex)

    Object.assign(this.formState, {
      if_type,
      name,
      if_matching,
      if_else_matching,
      if_next,
      if_else_next,
      else_next,
      ifOption
    })
    // 左侧
    emitter.on('if_node', ({ type, data }) => {
      const node = (this as any).getNode()
      if (node.id == data.targetNodeId) {
        if (type == 'add') {
          if (
            data.sourceAnchorId.indexOf('receive') === 0 ||
            data.sourceAnchorId.indexOf('http') === 0
          ) {
            this.formState.ifOption = [
              {
                label: data.sourceAnchorId.indexOf('receive') === 0 ? '收号' : '外部调用',
                value: data.sourceNodeId
              }
            ]
            this.formState.if_matching.forEach((item) => {
              item.nodeId = data.sourceNodeId
              item.type = data.sourceAnchorId.indexOf('receive') === 0 ? 1 : 2
            })

            this.formState.if_else_matching.forEach((item) => {
              item.nodeId = data.sourceNodeId
              item.type = data.sourceAnchorId.indexOf('receive') === 0 ? 1 : 2
            })
          }
        }
        if (type == 'delete') {
          this.formState.if_matching.forEach((item) => {
            item.nodeId = ''
            item.type = ''
          })

          this.formState.if_else_matching.forEach((item) => {
            item.nodeId = ''
            item.type = ''
          })
          this.formState.ifOption = []
        }
      }
    })
    // 右侧
    emitter.on('if_target', (val) => {
      const node = (this as any).getNode()
      const graph = (this as any).getGraph()
      const { nodes } = graph
      const index = nodes.findIndex((item) => item.id === node.id)
      this.formState.if_next = `${this.nodeIdx}-if`
      const obj = cloneDeep(nodes[index].properties)
      const updatedNode = { ...obj, ...this.formState }
      useStore.getLf.setProperties(node.id, updatedNode)
    })
    emitter.on('if_target2', (val) => {
      const node = (this as any).getNode()
      const graph = (this as any).getGraph()
      const { nodes } = graph
      const index = nodes.findIndex((item) => item.id === node.id)
      this.formState.if_else_next = `${this.nodeIdx}-else-if`
      const obj = cloneDeep(nodes[index].properties)
      const updatedNode = { ...obj, ...this.formState }
      useStore.getLf.setProperties(node.id, updatedNode)
    })
    emitter.on('if_target3', (val) => {
      const node = (this as any).getNode()
      const graph = (this as any).getGraph()
      const { nodes } = graph
      const index = nodes.findIndex((item) => item.id === node.id)
      this.formState.else_next = `${this.nodeIdx}-else`
      const obj = cloneDeep(nodes[index].properties)
      const updatedNode = { ...obj, ...this.formState }
      useStore.getLf.setProperties(node.id, updatedNode)
    })
  },
  methods: {
    updateProperties() {
      const node = (this as any).getNode()
      const graph = (this as any).getGraph()
      const { nodes } = graph
      const index = nodes.findIndex((item) => item.id === node.id)

      if (index !== -1) {
        this.$nextTick(() => {
          const heightValue = document.getElementById('if-box').offsetHeight
          const obj = cloneDeep(nodes[index].properties)
          const updatedNode = { ...obj, ...this.formState, height: heightValue }

          // 更新节点属性
          useStore.getLf.setProperties(node.id, updatedNode)

          // 更新连线位置 - 参考menu.vue的实现
          this.updateConnectedEdges()
        })
      }
    },

    // 添加更新连线的方法
    updateConnectedEdges() {
      const node = (this as any).getNode()
      const lf = useStore.getLf
      const connectedEdges = lf.getNodeEdges(node.id)
      const nodeModel = lf.getNodeModelById(node.id)
      const anchors = nodeModel.anchors || nodeModel.getDefaultAnchor()

      // 获取右侧锚点并按Y坐标排序
      const rightAnchors = anchors
        .filter((anchor) => anchor.x > nodeModel.x)
        .sort((a, b) => a.y - b.y)

      connectedEdges.forEach((edge) => {
        // 只更新从此节点出发的边
        if (edge.sourceNodeId === node.id) {
          const anchorIndex = this.getAnchorIndexFromId(edge.sourceAnchorId)
          if (anchorIndex >= 0 && anchorIndex < rightAnchors.length) {
            const newAnchor = rightAnchors[anchorIndex]

            // 更新边的起始点
            const edgeModel = lf.getEdgeModelById(edge.id)
            if (edgeModel) {
              edgeModel.updateStartPoint({
                x: newAnchor.x,
                y: newAnchor.y
              })

              // 更新文本位置
              if (edgeModel.text) {
                edgeModel.text.x = (edgeModel.startPoint.x + edgeModel.endPoint.x) / 2
                edgeModel.text.y = (edgeModel.startPoint.y + edgeModel.endPoint.y) / 2
              }
            }
          }
        }
      })
    },

    // 从锚点ID获取索引
    getAnchorIndexFromId(anchorId: string): number {
      const match = anchorId.match(/_([0-9]+)$/)
      if (match) {
        const index = parseInt(match[1]) - 1 // 减1因为第一个是左侧锚点
        return Math.max(0, index)
      }
      return 0
    },
    // 删除节点
    delNode() {
      const node = (this as any).getNode()
      ElMessageBox.confirm('确定要删除此节点吗？', '提示', {
        confirmButtonText: '确 认',
        cancelButtonText: '取 消'
      }).then(() => {
        useStore.getLf.deleteNode(node.id)
      })
    },
    // 复制节点
    copyNode() {
      this.visible = false
      const node = (this as any).getNode()
      const CloneNode = useStore.getLf.cloneNode(node.id)
      useStore.getLf.changeNodeId(CloneNode.id, this.id + generateRandomString(6))
    },
    // 高度
    computedHeight() {},
    addIf() {
      this.formState.if_matching = [
        ...this.formState.if_matching,
        {
          nodeId: '',
          type: this.formState.if_matching[0].type ? this.formState.if_matching[0].type : '',
          query: '',
          value: ''
        }
      ]
      this.updateProperties()
    },
    delIf(index) {
      if (index != 0) {
        this.formState.if_matching.splice(index, 1)
        this.$nextTick(() => {
          this.updateProperties()
        })
      }
    },
    addIfElse() {
      this.formState.if_else_matching = [
        ...this.formState.if_else_matching,
        {
          nodeId: '',
          type: this.formState.if_else_matching[0].type
            ? this.formState.if_else_matching[0].type
            : '',
          query: '',
          value: ''
        }
      ]
      this.updateProperties()
    },
    clearElse(index) {
      if (index != 0) {
        this.formState.if_else_matching.splice(index, 1)
        this.$nextTick(() => {
          this.updateProperties()
        })
      }
    }
  }
})
</script>
<style scoped>
.playback-content {
  border-radius: 8px;
  border: 1px solid #f0f0f0;
}
.playback {
  padding: 16px;
  box-shadow: 0 2px 4px #1f23291f;
  border: 2px solid #fff !important;
  background: #ffffff;
  border-radius: 8px;
}
.img-box {
  background: linear-gradient(270deg, #9258f7 0%, #14c0ff 100%);
  width: 22px;
  height: 22px;
  display: flex;
  align-items: center;
  justify-content: center;
  border-radius: 4px;
  margin-right: 8px;
}
.playback-tite {
  display: flex;
  align-items: center;
  margin-bottom: 16px;
  justify-content: space-between;
}
.w-16 {
  width: 16px;
}
.h-16 {
  height: 16px;
}
.titles {
  font-size: 16px;
  color: #1f2329;
  font-weight: bold;
}
.flex {
  display: flex;
  align-items: center;
}
.p-8 {
  padding: 4px 8px;
  cursor: pointer;
  font-size: 14px;
  text-align: center;
}
.gap {
  gap: 10px;
}
.if_box {
  background-color: #f5f6f7;
  padding: 10px;
  margin-bottom: 10px;
  border-radius: 5px;
}
.dis {
  cursor: not-allowed !important;
}
</style>
